﻿using System;
using System.Drawing;
using ttbit;
using ttbit.form;

namespace lib.bitform.test
{
    public class Testor
    {

        public static void Start()
        {
            var tester = new Testor();
            tester.Run();


        }
        IBatcher batcher;
        TestFont font;
        ITexture texlogo;
        public void Run()
        {
            Env.Graphic.OnRender += OnRender;
            Env.SetEvent_OnUpdate(OnUpdate);
            Env.SetEvnet_OnChangeSize(OnChangeSize);

            texlogo = LoadTexture("cat");

            var fontfs = Env.RootPack.GetPackItem("hzk16").Bytes;//.ttfont");//"hzk16.ttfont"
            font = new TestFont();
            font.LoadFont(fontfs);
            batcher = Env.Graphic.CreateRenderer_Batcher(Env.Graphic.MainScreen);
        }
        static ITexture LoadTexture(string name)
        {
            var res = Env.RootPack.GetPackItem(name);
            if (res.Type == ".ttimg")
            {
                ImgData img = new ImgData();
                using var ms = new System.IO.MemoryStream(res.Bytes);
                using var mr = new System.IO.BinaryReader(ms);
                img.Read(mr);

                var tex = Env.Graphic.CreateStaticTexture(img.width, img.height, img.format == TTIMGFormat.RGBA ? TextureFormat.RGBA32 : TextureFormat.R8,img.pixel);
                return tex;
            }
            if (res.Type == ".jpg" || res.Type == ".png")
            {
                var bts = res.Bytes;

                BitmapData img = new BitmapData();
                img.LoadRGBA(bts);

                var tex = Env.Graphic.CreateStaticTexture(img.width, img.height,  TextureFormat.RGBA32,img.data);
                return tex;

            }
            return null;
        }

        void OnRender()
        {
            batcher.BeginDraw();

            var width = texlogo.width;
            var height= texlogo.height;
            if(width>256)width = 256; 
            if(height>256)height = 256;
            batcher.DrawRect(texlogo,null,
                new RectangleF(0,0,width,height),
                new Rectangle(0, 0, texlogo.width, texlogo.height), Color32.White);
            font.DrawFont(batcher, "abcdefghijklmnopqrst Hello 地球人", new Vector2(32, 32));

            batcher.EndDraw();
        }
        void OnUpdate(float delta)
        {
            batcher.Scale = 2.0f;
            batcher.LookAt = new Vector2(16, 16);
            Env.Graphic.MainScreen.ClearColor = ColorF.FromARGB(1, 1, 0, 1);

        }
        void OnChangeSize(int width, int height)
        {

        }
    }
}
